package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.*;
import com.burgeon.backend.SHOP.entity.presell.Earnest;
import com.burgeon.backend.SHOP.mappers.AppPresellMapper;
import com.burgeon.backend.SHOP.mappers.RefundMapper;
import com.burgeon.backend.SHOP.rest.*;
import com.burgeon.backend.SHOP.service.*;
import com.burgeon.backend.SHOP.service.ex.ErrorDataExceptionApp;
import com.burgeon.backend.SHOP.service.util.MathUtil;
import com.burgeon.backend.SHOPBACKEND.entity.ShopKf;
import com.burgeon.backend.SHOPBACKEND.mappers.WeChatKfMapper;
import com.burgeon.backend.SHOPBACKEND.push.UmengUtil;
import com.burgeon.backend.SHOPBACKEND.rest.QuerryYcRetRetailById;
import com.burgeon.backend.SHOPBACKEND.rest.weixin.findEmployeeByPhone;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.entity.JiPushMsg;
import com.burgeon.backend.entity.User;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.ex.ErrorDataException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.burgeon.backend.SHOP.service.Impl.OrderServiceImpl.getOrderIdByUUId;

@Service
public class RefundServiceImpl implements RefundService {
    private final static Log logger = LogFactory.getLog(RefundService.class);
    @Autowired
    private RefundMapper refundMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private PayWechatService payWechatService;
    @Autowired
    private ShopMessageTemplateService shopMessageTemplateService;
    @Autowired
    private EmpNotificationMessageService empNotificationMessageService;
    @Autowired
    private WeChatKfMapper weChatKfMapper;
    @Autowired
    private AppPresellMapper appPresellMapper;


    @Override
    public void sendMail(String id, String oid, String FASTNO, String FASTGS, String token, String uid) throws ErrorDataExceptionApp {
        Info info = GetInfo(token);
        ModRefundMailData modRefundMailData = new ModRefundMailData(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            modRefundMailData.getData(id, FASTNO, FASTGS, "3");
            refundMapper.upOrderState(oid, "3");
            //发送通知
            //pushSendMail(id, oid, FASTNO, FASTGS, token, uid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataExceptionApp(e.getMessage());
        }

    }

    //退货邮件发货后发送通知
    private void pushSendMail(String id, String oid, String FASTNO, String FASTGS, String token, String uid) {
        Info info = GetInfo(token);
        System.err.println("退货邮件发货后发送通知");
        //查询专属导购
        User user = refundMapper.GetUserPhone(uid);
        //根据手机号查询用户服务导购手机号
        findEmployeeByPhone findEmployeeByPhone = new findEmployeeByPhone(info.getUrl(), info.getAccount(), info.getPassword());
        QuerryYcRetRetailById querryYCRetailout = new QuerryYcRetRetailById(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            String empPhone = findEmployeeByPhone.getData(user.getPhone());
            RefundErpVO refundErpVO = querryYCRetailout.getData(id);
            //1.判断是否有智慧导购App
            if ("Y".equals(info.getIs_app())) {
                //2.有app的客户,发送友盟通知，
                JiPushMsg jiPushMsg = new JiPushMsg();
                //jiPushMsg.setAliasList(aliasList);
                jiPushMsg.setNotification_title("VIP退货邮件发货通知");
                jiPushMsg.setMsg_title("VIP退货邮件发货通知");
                jiPushMsg.setMsg_content("VIP" + user.getPhone() + "退货邮件发货" + ",快递公司：" + FASTGS + "云仓订单编号：" + refundErpVO.getYcDoNo());
                jiPushMsg.setExtrasparam(id);
                //jiPushMsg.setAccount(info.getAccount());
                //b.友盟工具
                UmengUtil umengUtil = new UmengUtil();
                String channel = "com.bojun.rfmapplication.activity.home.OrderListActivity";
                //2.1为专属导购发送友盟推送
                Boolean t = umengUtil.sendAndroidCustomizedcast(empPhone, "phone",
                        jiPushMsg.getNotification_title(), jiPushMsg.getMsg_title(),
                        jiPushMsg.getMsg_content(), jiPushMsg.getExtrasparam(), channel, "3");
            } else {
//                //发送给微信客服
//                ArrayList<ShopKf> shopKfs = weChatKfMapper.getKf(token);
//                for (ShopKf shopKf:shopKfs) {
//                    empNotificationMessageService.sendEmpRefund(shopKf.getKfNick(),user.getName(),user.getPhone(),shopKf.getOpenid(),id,token);
//                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Override
    public HashMap getItemMailData(String id, String token) {
        RefundVO data = refundMapper.getRefundRecord(id);
        Info info = GetInfo(token);
        GetRefundById getRefundById = new GetRefundById(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getRefundById.getData(data.getErpId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void test(String id) {


    }

    //定时
    @Override
    public void timedTask() {
        List<Info> accList = accountMapper.getShopAccountAll();
        //同步所有账号

        for (Info info : accList) {
            if (
                    !"lfwd".equals(info.getToken())

            ) {
                continue;
            }
            //同步待发货
            List<RefundVO> refundList = refundMapper.getRefundRecordByToken(info.getToken());
            GetRefundByAccount getRefundByAccount = new GetRefundByAccount(info.getUrl(), info.getAccount(), info.getPassword());
            ModRefundState modRefundState = new ModRefundState(info.getUrl(), info.getAccount(), info.getPassword());
            ModRefundRET_State modRefundRET_state = new ModRefundRET_State(info.getUrl(), info.getAccount(), info.getPassword());

            ArrayList<Invoices> data = getRefundByAccount.getData();
            for (Invoices invoices : data) {
                try {
                    for (RefundVO refundVO : refundList) {
                        if (refundVO.getErpId().equals(invoices.getID())) {
                            // 0:未发起退款 1:待审核,2:待发货,3:待收货,4:待退款,5:退款中,6:完成
                            switch (invoices.getYC_RET_STATUS()) {

                                case "待审核":
                                    //同步退款单状态
                                    System.err.println("待审核:" + refundVO.getOiId());
                                    refundMapper.upOrderState(refundVO.getOiId(), "1");
                                    break;
                                case "已驳回":
                                    System.err.println("已驳回:" + refundVO.getOiId());
                                    refundMapper.upOrderState(refundVO.getOiId(), "-1");
                                    if ("未同步".equals(invoices.getIS_UP())) {

                                        String value = "尊贵的会员，您的退款申请未通过，点击详情，进入退款列表页";
                                        shopMessageTemplateService.sendRefundMessageTemplate(
                                                value, refundVO.getRefundId(), invoices.getTOT_AMT_ACTUALSJ(),
                                                refundVO.getOpenid(), info.getToken());

                                        modRefundState.getData(invoices.getID(), "YC_V2_RET_RETAIL", "IS_UP", "2");
                                    }
                                    break;
                                case "待发货":
                                    //同步退款单状态
                                    refundMapper.upOrderState(refundVO.getOiId(), "2");
                                    //发送通知更改同步字段

                                    if ("未同步".equals(invoices.getIS_UP())) {
                                        // String value = "尊敬的客户,你们退款申请已通过,请将商品退回";
                                        String value = "尊贵的会员，您的退款申请已通过，请及时回寄商品，点击详情，进入退款列表页";
                                        shopMessageTemplateService.sendRefundMessageTemplate(
                                                value, refundVO.getRefundId(), invoices.getTOT_AMT_ACTUALSJ(),
                                                refundVO.getOpenid(), info.getToken());

                                        modRefundState.getData(invoices.getID(), "YC_V2_RET_RETAIL", "IS_UP", "2");
                                    }

                                    break;
                                case "待收货":
                                    //同步退款单状态
                                    refundMapper.upOrderState(refundVO.getOiId(), "3");
                                    break;
                                case "待退款":
                                    //同步退款单状态
                                    refundMapper.upOrderState(refundVO.getOiId(), "4");
                                    break;
                                case "退款中":
                                    //同步退款状态
                                    refundMapper.upOrderState(refundVO.getOiId(), "5");
                                    //退款 改状态 完成

                                    if ("YS".equals(refundVO.getOrderType())) {
                                        OpenToBookingARefund(refundVO,invoices,info,modRefundRET_state,modRefundState);
                                        break;
                                    }

                                    HashMap<String, String> refund =
                                            performRefund(
                                                    refundVO.getOrderId(), refundVO.getTotal(), invoices.getTOT_AMT_ACTUALSJ(),
                                                    refundVO.getMailFee(), invoices.getRET_DESCRIPTION(),
                                                    refundVO.getRefundId(), info.getToken()
                                            );
                                    if ("SUCCESS".equals(refund.get("returnCode")) && "SUCCESS".equals(refund.get("resultCode"))) {

                                        //改小程序退款单状态 已完成

                                        modRefundRET_state.getData(invoices.getID(), "YC_V5_RET_RETAIL", "6");
                                        refundMapper.upOrderState(refundVO.getOiId(), "6");

                                        if ("未同步".equals(invoices.getIS_UPRET())) {
                                            String value = "尊敬的客户,本次退款已完成,请注意查收";
                                            shopMessageTemplateService.sendRefundMessageTemplate(
                                                    value, refundVO.getRefundId(), invoices.getTOT_AMT_ACTUALSJ(),
                                                    refundVO.getOpenid(), info.getToken());
                                            //发通知 改同步字段
                                            //更改同步字段
                                            modRefundState.getData(invoices.getID(), "YC_V5_RET_RETAIL", "IS_UPRET", "2");
                                        }

                                    } else {
                                        //不成功 写入原因
                                        refund.get("errCodeDes");
                                        modRefundState.getData(invoices.getID(), "YC_V5_RET_RETAIL", "RE_ERROR_DESCRIPTION", refund.get("errCodeDes"));
                                    }

                                    break;
                            }
                            System.err.println(refundVO.getId() + "同步了");
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println(invoices);
                }
            }

        }

    }


    /**
     * 预售退款
     */

    private void OpenToBookingARefund(RefundVO refundVO, Invoices invoices, Info info,
                                      ModRefundRET_State modRefundRET_state, ModRefundState modRefundState)
            throws Exception {
        //退定金 退尾款

        Earnest earnest = appPresellMapper.getEarnestDataById(refundVO.getOid());
        String refundId = getOrderIdByUUId();//定金退款单号
        //定金退款
        HashMap<String, String> earnestRefund =
                performRefund(
                        earnest.getOrderId(), earnest.getTpayed(), earnest.getTpayed(),
                        "0", invoices.getRET_DESCRIPTION(),
                        refundId, info.getToken()
                );
        appPresellMapper.upEarnestRefund(earnest.getId(),refundId,"T");
        logger.error(earnestRefund);

        Thread.sleep(100);
        //尾款退款
        HashMap<String, String> refund =
                performRefund(
                        refundVO.getOrderId(), earnest.getRem(), earnest.getRem(),
                        refundVO.getMailFee(), invoices.getRET_DESCRIPTION(),
                        refundVO.getRefundId(), info.getToken()
                );



        if ("SUCCESS".equals(refund.get("returnCode")) && "SUCCESS".equals(refund.get("resultCode"))) {

            //改小程序退款单状态 已完成

            modRefundRET_state.getData(invoices.getID(), "YC_V5_RET_RETAIL", "6");
            refundMapper.upOrderState(refundVO.getOiId(), "6");

            if ("未同步".equals(invoices.getIS_UPRET())) {
                String value = "尊敬的客户,本次退款已完成,请注意查收";
                shopMessageTemplateService.sendRefundMessageTemplate(
                        value, refundVO.getRefundId(), invoices.getTOT_AMT_ACTUALSJ(),
                        refundVO.getOpenid(), info.getToken());
                //发通知 改同步字段
                //更改同步字段
                modRefundState.getData(invoices.getID(), "YC_V5_RET_RETAIL", "IS_UPRET", "2");
            }

        } else {
            //不成功 写入原因
            refund.get("errCodeDes");
            modRefundState.getData(invoices.getID(), "YC_V5_RET_RETAIL", "RE_ERROR_DESCRIPTION", refund.get("errCodeDes"));
        }

    }

    //退款接口
    private HashMap<String, String> performRefund(
            String orderid, String total, String price, String mailFee,
            String cause, String refundId, String token) {
        //订单号 退款单号 订单总价 退款价格 原因
        if (null == mailFee) {
            mailFee = "0";
        }
        System.err.println("mail=" + mailFee);
        System.err.println("total=" + total);
        BigDecimal totalB = MathUtil.multiply(
                MathUtil.add(new BigDecimal(total), new BigDecimal(mailFee), 0),
                new BigDecimal(100), 0);

        BigDecimal priceB = MathUtil.multiply(new BigDecimal(price), new BigDecimal(100), 0);
        return payWechatService.goodsRefund(token, orderid, priceB.toString(),
                totalB.toString(), cause, refundId);


    }

    @Override
    public RefundVO getItemData(String id, String token) throws ErrorDataExceptionApp {
        RefundVO data = refundMapper.getRefundRecord(id);
        if (null == data) {
            throw new ErrorDataExceptionApp("未找到数据");
        }
        data.setTotal(
                String.valueOf(
                        MathUtil.multiply(
                                new BigDecimal(data.getPrice()),
                                new BigDecimal(data.getNum())
                        )
                )
        );
        return data;
    }

    @Override
    public List<Refund> getData(String uid, String token) {
        //砍价/积分商品不能退货
        return refundMapper.FindData(uid, token);
    }

    @Override
    public void applyForGoods(String id, String num, String cause, String token, String uid) throws ErrorDataExceptionApp {
        if (null == id) {
            throw new ErrorDataException("出现错误,订单id为空");
        }

        Info info = GetInfo(token);
        //根据id查询订单详情
        OrderItem orderItem = refundMapper.FindOrderData(id);


        String refundId = getOrderIdByUUId();
        //确认数量 价格
        if (null == orderItem) {
            throw new ErrorDataExceptionApp("订单不存在");
        }

        if (null == orderItem.getOid()) {
            throw new ErrorDataExceptionApp("订单不存在");
        }
        if (Integer.parseInt(num) > Integer.parseInt(orderItem.getGoodsNum())) {
            throw new ErrorDataExceptionApp("请输入正确的数量");
        }

        /*
        if (Double.parseDouble(price)>Double.parseDouble(orderItem.getGoodsPrice())*Integer.parseInt(num)){
            throw new ErrorDataExceptionApp("请输入正确的价格");
        }*/

        Refund refund = new Refund();
        refund.setCode(orderItem.getCode());
        refund.setOrderId(orderItem.getOid());
        refund.setCause(cause);
        refund.setPrice(orderItem.getGoodsPrice());
        refund.setNum(num);
        refund.setRefundId(refundId);
        refund.setTotalPrice(String.valueOf(
                MathUtil.multiply(
                        new BigDecimal(orderItem.getGoodsPrice()),
                        new BigDecimal(num)
                )
        ));

        //写入erp
        CreateRefund createRefund = new CreateRefund(info.getUrl(), info.getAccount(), info.getPassword());
        String objid = "";
        System.err.println("refund=" + refund);
        try {
            objid = createRefund.getData(refund);
            /***发送通知给客服**/
            PushKf(token, uid, refundId, refundId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataExceptionApp(e.getMessage());
        }
        //写入数据库 记录erp退款单id

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(new Date());

        RefundRecord refundRecord = new RefundRecord();
        refundRecord.setRefundId(refundId);
        refundRecord.setCause(cause);
        refundRecord.setCode(orderItem.getCode());
        refundRecord.setErpId(objid);
        refundRecord.setOtid(orderItem.getId());
        refundRecord.setNum(num);
        refundRecord.setPrice(orderItem.getGoodsPrice());
        refundRecord.setToken(token);
        refundRecord.setCreateTime(dateString);

        refundMapper.CreateRefundRecord(refundRecord);

        //改变状态
        refundMapper.upOrderState(orderItem.getId(), "1");//改变状态1 退款中

    }

    //发送退货通知
    public void PushKf(String token, String uid, String objid, String refundId) {
        System.err.println("发送退货通知");
        Info info = GetInfo(token);
        //查询专属导购
        User user = refundMapper.GetUserPhone(uid);
        //根据手机号查询用户服务导购手机号
        findEmployeeByPhone findEmployeeByPhone = new findEmployeeByPhone(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            String empPhone = findEmployeeByPhone.getData(user.getPhone());
//            //1.判断是否有智慧导购App
//            if("Y".equals(info.getIs_app())){
//                //2.有app的客户,发送友盟通知，
//                JiPushMsg jiPushMsg =new JiPushMsg();
//                //jiPushMsg.setAliasList(aliasList);
//                jiPushMsg.setNotification_title("VIP退货通知");
//                jiPushMsg.setMsg_title("VIP退货通知");
//                jiPushMsg.setMsg_content("VIP"+user.getPhone()+"发起退货,线上退货单号"+refundId);
//                jiPushMsg.setExtrasparam(objid);
//                //jiPushMsg.setAccount(info.getAccount());
//                //b.友盟工具
//                UmengUtil umengUtil = new UmengUtil();
//                String channel = "com.bojun.rfmapplication.activity.home.OrderListActivity";
//                //2.1为专属导购发送友盟推送
//                Boolean t = umengUtil.sendAndroidCustomizedcast(empPhone,"phone",
//                        jiPushMsg.getNotification_title(), jiPushMsg.getMsg_title(),
//                        jiPushMsg.getMsg_content(), jiPushMsg.getExtrasparam(), channel, "3");
//
//            }else {
            //3.没有发送微信模板消息
            ArrayList<ShopKf> shopKfs = weChatKfMapper.getKf(token);
            for (ShopKf shopKf : shopKfs) {
                empNotificationMessageService.sendEmpRefund(shopKf.getKfNick(), user.getName(), user.getPhone(), shopKf.getOpenid(), objid, token);
//                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }


}
